const formatTime = times => {

  console.log(typeof times)

  if (typeof times == 'number' || typeof times == 'string') {
    times = new Date(times)
  }

  const year = times.getFullYear()
  const month = times.getMonth() + 1
  const day = times.getDate()
  const hour = times.getHours()
  const minute = times.getMinutes()
  const second = times.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatResponse(response, success, fail) {
  var responseData = typeof response === 'string' ? JSON.parse(response) : response;
  if (responseData.statusCode == 200) {
    _formatDemo2doResponse(responseData.data, success, fail);
  } else {
    console.log("utils.js - request faild with response" + response);
    console.log("utils.js - request faild with statusCode [" + responseData.statusCode + "]")
    typeof fail == "function" && fail(responseData.statusCode, responseData.data.message);
  }
}


function _formatDemo2doResponse(data, success, fail) {

  var response = typeof data === 'string' ? JSON.parse(data) : data;

  if (response.code == 0) {
    typeof success == "function" && success(response.data);
  } else {
    typeof fail == "function" && fail(response.code, response.message);
  }
}

module.exports = {
  formatTime: formatTime,
  formatResponse: formatResponse
}
